package com.ljh.mall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljh.common.constant.ProductConstant;
import com.ljh.common.dto.SkuHasStockDto;
import com.ljh.common.dto.SkuReductionDTO;
import com.ljh.common.dto.SpuBoundsDTO;
import com.ljh.common.dto.es.SkuESModel;
import com.ljh.common.utils.R;
import com.ljh.mall.product.entity.*;
import com.ljh.mall.product.feign.CouponFeginService;
import com.ljh.mall.product.feign.SearchFeginService;
import com.ljh.mall.product.feign.WareSkuFeginService;
import com.ljh.mall.product.service.*;
import com.ljh.mall.product.vo.*;
import com.ljh.common.dto.MemberPrice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljh.common.utils.PageUtils;
import com.ljh.common.utils.Query;

import com.ljh.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeginService couponFeginService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BrandService brandService;

    @Autowired
    WareSkuFeginService wareSkuFeginService;
    @Autowired
    SearchFeginService searchFeginService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * SPU信息检索
     * 分页查询
     * 分类 品牌 状态 关键字查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 设置对应的检索条件
        // 1、关键字查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            //
            wrapper.and((w) ->{
                w.eq("id", key)
                        .or().like("spu_name",key)
                        .or().like("spu_description",key);
            });
        }
        // status
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        // catalogId
        String catelogId = (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        // brandId
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        //todo 3.15 发现问题 记得补上
        List<SpuInfoVO> list = page.getRecords().stream().map(spu ->{
            Long catelogId1 = spu.getCatalogId();
            CategoryEntity categoryEntity = categoryService.getById(catelogId1);
            Long brandId1 = spu.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId1);
            SpuInfoVO vo = new SpuInfoVO();
            BeanUtils.copyProperties(spu, vo);
            vo.setCatalogName(categoryEntity.getName());
            vo.setBrandName(brandEntity.getName());

            return vo;
        }).collect(Collectors.toList());
        IPage<SpuInfoVO> iPage = new Page<>();
        iPage.setRecords(list);
        iPage.setPages(page.getPages());
        iPage.setCurrent(page.getCurrent());

        return new PageUtils(iPage);
    }

    /**
     * 保存商品的发布信息
     * @param spuInfoVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVO spuInfoVo) {
        // 1.保存spu的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo,spuInfoEntity);
        this.save(spuInfoEntity);
        // 2.保存spu的详情信息 pms_spu_info_desc
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decripts = spuInfoVo.getDecript();
        infoDescEntity.setDecript(String.join(",",decripts));
        spuInfoDescService.save(infoDescEntity);

        // 3.保存图集信息 pms_spu_images

        List<SpuImagesEntity> images = spuInfoVo.getImages().stream().map(item -> {
            SpuImagesEntity entity = new SpuImagesEntity();
            entity.setSpuId(spuInfoEntity.getId());
            entity.setImgUrl(item);
            return entity;
        }).collect(Collectors.toList());
        // 3.1 进行批量新增
        spuImagesService.saveBatch(images);

        // 4.保存规格参数 pms_product_attr_value
        List<ProductAttrValueEntity>productAttrValueEntities = spuInfoVo.getBaseAttrs().stream().map(item -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setSpuId(spuInfoEntity.getId());
            productAttrValue.setAttrId(item.getAttrId());
            productAttrValue.setAttrValue(item.getAttrValues());
            productAttrValue.setQuickShow(item.getShowDesc());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValue.setAttrName(attrEntity.getAttrName());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5.保存当前的spu对应的所有的sku信息 SkuInfoEntity
        List<Skus> skus =spuInfoVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSkuName(item.getSkuName());
                skuInfoEntity.setPrice(item.getPrice());
                skuInfoEntity.setSkuTitle(item.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());

                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);

                List<Images> images1 = item.getImages();
                String defaultImage= "";
                for (Images i:images1){
                    if(i.getDefaultImg() == 1){
                        // 表示是默认的图片
                        defaultImage = i.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                // 进行保存
                skuInfoService.save(skuInfoEntity);
                // 5.2 保存sku的图片信息 pms_sku_image
                List<SkuImagesEntity> skuImagesEntityList = images1.stream().map(images2 -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(images2.getImgUrl());
                    skuImagesEntity.setDefaultImg(images2.getDefaultImg());
                    return skuImagesEntity;
                }).filter(images2 -> {
                    return images2.getDefaultImg() == 1;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);
                // 5.3 保存满减信息，折扣，会员价 mall_sms: sms_sku_ladder sms_full_reduction sms_member_price
                SkuReductionDTO dto = new SkuReductionDTO();
                BeanUtils.copyProperties(item,dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                // 设置会员价
                if (item.getMemberPrice() != null && item.getMemberPrice().size() > 0) {
                    List<MemberPrice> list = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice mDto = new MemberPrice();
                        BeanUtils.copyProperties(memberPrice, mDto);
                        return mDto;
                    }).collect(Collectors.toList());
                    dto.setMemberPrice(list);
                    R r = couponFeginService.saveFullReductionInfo(dto);
                    if(r.getCode() != 0){
                        log.error("调用Coupon服务处理满减、折扣，会员价操作失败...");
                    }
                }
                //  5.4 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    attrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    attrValueEntity.setAttrId(attr.getAttrId());
                    attrValueEntity.setAttrName(attr.getAttrName());
                    attrValueEntity.setAttrValue(attr.getAttrValue());
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

            });
        }
        // 6.保存spu的积分信息：mall-sms: sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds,spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeginService.saveSpuBounds(spuBoundsDTO);
        if (r.getCode() != 0){
            log.error("调用Coupon服务存储积分信息操作失败");
        }

    }

    @Override
    public void up(Long spuId) {
        List<SkuESModel> skuEs = new ArrayList<>();
        //1.根据spuId查询相关的信息 封装到SkuESModel对象中
        // 根据spuID找到对应的SKU信息  pms_sku_info
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 对应的规格参数  根据spuId来查询规格参数信息  pms_product_attr_value
        List<SkuESModel.Attrs> attrsModel = getAttrsModel(spuId);

        // 需要根据所有的SKU信息 获取对应的库存信息(根据skuIds获取对应的库存状态)---》远程调用
        List<Long> skuIds = skus.stream().map(item->{
            return item.getSkuId();
        }).collect(Collectors.toList());
        Map<Long, Boolean> skusHasStockMap = getSkusHasStock(skuIds);
        System.out.println("库存中"+skusHasStockMap);
        // 2.远程调用mall-search的服务，将SukESModel中的数据存储到ES中
        // 封装 SkuESModel
        List<SkuESModel> skuESModels = skus.stream().map(item -> {
            SkuESModel model = new SkuESModel();
            BeanUtils.copyProperties(item, model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            // hasStock 是否有库存 --》 库存系统查询  一次远程调用获取所有的skuId对应的库存信息
            if (skusHasStockMap == null){
                model.setHasStock(true);
            } else {
                // skuid 查找对应的 库存是否存在
                model.setHasStock(skusHasStockMap.get(item.getSkuId()));
            }
            // hotScore 热度分 --> 默认给0即可
            model.setHotScore(0l);
            // 品牌和类型的名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            model.setCatalogName(category.getName());
            model.setAttrs(attrsModel);

            return model;
        }).collect(Collectors.toList());
        // 将SkuESModel中的数据存储到ES中
        R r = searchFeginService.productStatusUp(skuESModels);
        System.out.println("-------------->"+r.getCode());
        if (r.getCode() == 0){
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }




    }

    @Override
    public List<OrderItemSpuInfoVO> getOrderItemSpuInfoBySpuId(Long[] spuIds) {
        List<OrderItemSpuInfoVO> list = new ArrayList<>();
        for (Long spuId:spuIds){
            OrderItemSpuInfoVO vo = new OrderItemSpuInfoVO();
            SpuInfoEntity spuInfoEntity = this.getById(spuId);
            vo.setId(spuId);
            vo.setSpuName(spuInfoEntity.getSpuName());
            vo.setBrandId(spuInfoEntity.getBrandId());
            vo.setCatalogId(spuInfoEntity.getCatalogId());
            // 根据品牌编号查询品牌信息
            BrandEntity brand = brandService.getById(spuInfoEntity.getBrandId());
            vo.setBrandName(brand.getName());
            // 根据 商品分类编号查询商品信息
            CategoryEntity category = categoryService.getById(spuInfoEntity.getCatalogId());
            vo.setCatalogName(category.getName());
            // 获取SPU的图片
            SpuInfoDescEntity byId = spuInfoDescService.getById(spuId);
            vo.setImg(byId.getDecript());
            list.add(vo);

        }
        // 根据SPUID查询出相关的信息
        return list;
    }

    /**
     *  根据skuId
     *  查询 库存的状态
     * @param skuIds
     * @return
     */
    private Map<Long,Boolean> getSkusHasStock(List<Long> skuIds){
        if(skuIds == null && skuIds.size() == 0) {
            return null;
        }
       try {
           // 获取sku 对应的仓库 是否有数据
           List<SkuHasStockDto> skusHasStock = wareSkuFeginService.getSkusHasStock(skuIds);
            Map<Long, Boolean> map = skusHasStock.stream().
                    collect(Collectors.toMap(skuHasStockDto -> skuHasStockDto.getSkuId(),skuHasStockDto -> skuHasStockDto.getHasStock()));

            return map;
       } catch (Exception e) {
           e.printStackTrace();
       }
        return null;
    }

    /**
     * 根据 attrIds 查询出  可检索的 数据
     * @param spuId
     * @return
     */
    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrsForSpuId(spuId);
        // 判断 attrs id 是否可 检索
        List<Long> attrIds = baseAttrs.stream().map(item -> {
           return item.getAttrId();
        }).collect(Collectors.toList());

        // 根据 attrIds 查询出  可检索的 数据
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        List<SkuESModel.Attrs> attrsModel = baseAttrs.stream().filter(item ->{
            // 返回 可检索的属性iD
           return searchAttrIds.contains(item.getAttrId());
        }).map(item -> {
            SkuESModel.Attrs attrs = new SkuESModel.Attrs();
            attrs.setAttrId(item.getAttrId());
            attrs.setAttrName(item.getAttrName());
            attrs.setAttrValue(item.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());
        /**
         *   attrId;
         *  String attrName;
         * String attrValue;
         */
        return attrsModel;
    }
}